using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using MemoryPack;
using UnityEngine;

public class ClientSocket 
{
    private Socket clientSocket;
    private string ip = "127.0.0.1";
    private int port = 8888;
    
    public ClientSocket()
    {
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //解析ip地址
        IPAddress ipAddress = IPAddress.Parse(ip);
        IPEndPoint endPoint = new IPEndPoint(ipAddress, port);
        //连接服务器
        clientSocket.BeginConnect(endPoint,OnClientCallBack, null);
        
    }

    private void OnClientCallBack(IAsyncResult ar)
    {
        clientSocket.EndConnect(ar);
        //连接成功后接受
        OnReceive();
    }
    
    private byte[] buffer = new byte[1024];
    public void OnReceive()
    {
        clientSocket.BeginReceive(buffer,0,buffer.Length,SocketFlags.None,OnReceiveCallBack,null);
    }

    private void OnReceiveCallBack(IAsyncResult ar)
    {
        clientSocket.EndReceive(ar);
        AccountResult accountResult=MemoryPackSerializer.Deserialize<AccountResult>(buffer);
        Debug.Log(accountResult.result+","+accountResult.msg);
        OnReceive();
    }

    public void OnSendData(byte[] bytes)
    {
        clientSocket.Send(bytes);
    }
    
}
